// xc_lshop/business/pro/edit.js
// var actbill = require('../../../xc/model/pro_contents')
var actbillclass = require('../../../xc/model/pro_class')
var actbill = require('../model/business_pro')

Page({
  mixins: [require('../../../xc/mixins/basicMixin')],

  /**
   * 页面的初始数据
   */
  data: {
    autosize: {
      maxHeight: 10,
      minHeight: 1
    },
    vildfield: {
      name: true,
      simg: true,
      realprice: true,
      bpid:true,
      spid:true,
    },
    vildfieldmesage: {
      name: "请填写产品名称",
      simg: "请上传小图",
      realprice: "请填写价格",
      bpid:"请选择大类",
      spid:"请选择小类",
    }
  },
  xcloaddata: function (options, config) {
    var that=this;
    this.getclass()
    if(options.id){
      this.getmodel(options.id)

    }else{
      this.emtypmodel(true)
    }
  },
  onClosepopup() {
    this.setData({
      classshow: false
    })
  },
  chooseclass(e) {
    console.log(e)
    var update = {
      classshow: true
    }
    var op = e.currentTarget.dataset.op;
    update['op'] = op
    var bpid = this.data.model.bpid
    if (op == 'bclass') {
      update['proclass'] = this.data.bclass
    } else {
      console.log("this.data.sclass[bpid]")
      console.log(this.data.sclass)
      console.log(bpid)

      console.log(this.data.sclass[bpid])
      if(this.data.sclass[bpid]){
        update['proclass'] = this.data.sclass[bpid]

      }else{
        update['proclass'] = []

      }

    }
    this.setData(update)
  },
  onconfirmclass(e) {
    var value = e.detail.value;
    var update={classshow: false}
    if(this.data.op=='bclass'){
      update['model.bpid']=value.id
    }else{
      update['model.spid']=value.id
    }
    this.setData(update)
    if(this.data.op=='bclass'){
      this.checkRule("bpid")
    }else{
      this.checkRule("spid")
    }
  },
  getclass() {
    console.log("ssssssssss")

    var that = this
    actbillclass.apiall().then(res => {
      console.log("res")
      if (res["status"] == 1) {
        console.log(res)
        var modellist=res["obj"]['modellist'];
        var bclass=[];
        var sclass={};

        for(var i in modellist){
          if(modellist[i]['pid']==0){
            bclass.push(modellist[i])
          }else{
            if(!sclass[modellist[i]['pid']]){
              sclass[modellist[i]['pid']]=[];
            }
            sclass[modellist[i]['pid']].push(modellist[i])
          }
        

        }
       console.log(bclass)
       console.log(sclass)

        that.setData({
          level: res["obj"]['level'],
          modellist: res["obj"]['modellist'],
          bclass:bclass,
          sclass:sclass,
        })
      }
    })
  },
  getmodel(id) {
    var that = this
    actbill.getmodel(id).then(res => {
      if (res.status == 1) {
        var xcmodelobj = res.obj;
        var numarr=['price','costprice','realprice'];
        for(var a in numarr){
          xcmodelobj[numarr[a]]=xcmodelobj[numarr[a]] / 100
        }
        var imgslist=xcmodelobj['imgslist'];
        var bimg=[]
        for(var i in imgslist){
          if(imgslist[i]['status']==1){
            bimg.push(imgslist[i]['imgurl'])
          }
        }
        xcmodelobj['bimg']=bimg
        // xcmodelobj['videourl']='https://cx002exrds.7mx7.com/images/5/2023/03/6424e4d30c41a.mp4'
        that.setData({
          model: xcmodelobj
        })
      }
    })
  },
  saveform: function (ev) {
    var that = this;
    var postmodel = this.data.model
    var res = this.checkForm();

    if (res.length==0) {
      if(postmodel['realprice']){
        postmodel['realprice']=postmodel['realprice'] * 100;
      }
      if(postmodel['price']){
        postmodel['price']=postmodel['price'] * 100;
      }
      if(postmodel['costprice']){
        postmodel['costprice']=postmodel['costprice'] * 100;
      }
      if(!postmodel['stock']){
        postmodel['stock']="99999"
      }

      actbill.editoraddpro(postmodel).then(function (result) {
        if (result["status"] == -1) {
          wx.showModal({
            title: result["message"],
            content: result["message"],
            showCancel: false
          })
        } else if (result["status"] == 1) {
          wx.showModal({
            title: postmodel.id?'修改成功':"增加成功",
            content: "操作成功",
            confirmText: "继续操作",
            cancelText: "返回列表",
            success: function (res) {
              that.triggerEvent("change", {
                op: "add",
              })
              if (res.cancel) {
                that.pageback()
                //返回列表
              } else {
                if(!postmodel.id){
                  that.emtypmodel(true)
                }
              }

            }
          })



        }



      })
    } else {
      
      wx.showModal({
        title: '错误',
        content: res.join(","),
        complete: (res) => {
          if (res.cancel) {
            
          }
      
          if (res.confirm) {
            
          }
        }
      })
    }
  },
  emtypmodel(restval) {
    var model = {
      id:0,
      bimg: [],
      name: "",
      about: "",
      status: "1",
      guigetype: "-1",
      unit: "件",
      contents: {
        cont: "",
        imgs: []
      }
    }
    if (restval) {
      this.setData({
        model
      })
    }
    return model;
  },
  changefrom: function (ev) {
    var val = ev.detail
    var field = ev.currentTarget.dataset.field;
    console.log("this.data.model")
    console.log(this.data.model)
    console.log(field)
    console.log(val)
    if(field=='videoimg' || field=='videourl'){
      this.setval(this.data.model, field, val[0])

    }else{
      this.setval(this.data.model, field, val)

    }

    this.checkRule(field)


  },
  onChangeradio(e){
    console.log("e")
    console.log(e)
    this.setData({
      'model.status':e.detail
    })

  },
  //验证规则
  checkRule(field) {
    var vildfield = Object.keys(this.data.vildfield);

    if (vildfield.indexOf(field) != -1) {
      var updatemodel = {};
     
      if(field=='spid' || field=='bpid' ){
        if(field=='spid' && this.data.level==1){
          updatemodel['vildfield.' + field] = true ;
        }else{
          updatemodel['vildfield.' + field] = this.data.model[field]>0 ? true : false;
        }
      }else
      if (Array.isArray(this.data.model[field])) {
        var len = this.data.model[field].length;
        updatemodel['vildfield.' + field] = len > 0 ? true : false;
      } else {
        updatemodel['vildfield.' + field] = this.data.model[field] ? true : false;
      }
      this.setData(updatemodel)
    }

  },
  setval: function (obj, fields, val) {
 
    var atrrfild = fields.split(".");
    var len = atrrfild.length;
    var tem = obj;
    var i = 0
    for (; i < len - 1; i++) {
      tem = tem[atrrfild[i]]
    }
    tem[atrrfild[i]] = val;
    console.log("tem")
    console.log(tem)

    // checkRule(field)
  },
  //验证表单
  checkForm: function (field) {
    var error = [];
    if (field) {
      this.checkRule(field)
    } else {
      var vildfield = this.data.vildfield;
      Object.keys(vildfield).forEach(item => {
        this.checkRule(item)
        if (!this.data.vildfield[item]) {
          error.push(this.data.vildfieldmesage[item])
        }
      })
    }
   
     return error;
    
  },
  
})